import axios from 'axios'
import qs from 'qs'
import merge from 'lodash/merge'
import SecurityUtil from '@/utils/security'
import router from '@/router/router'
import YT from '@/utils/YT'

/**
 * 通讯组件
 */
const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

/**
 * 请求地址处理
 * @param {String} actionName action方法名称
 * @returns {String}
 */
http.dataUrl = (actionName) => {
  return (process.env.NODE_ENV !== 'production' ? process.env.VUE_APP_API_PROXY_URL : process.env.VUE_APP_API_URL) + actionName + '.do'
}

/**
 * 报文是否加密
 * @returns {Boolean}
 */
http.isEncrypt = () => {
  if (process.env.VUE_APP_IS_ENCRYPT === 'true') {
    return true
  } else {
    return false
  }
}

/**
 * 请求拦截
 */
// http.interceptors.request.use(config => {
//   if (Vue.cookie) {
//     config.headers['Cookie'] = Vue.cookie.get('token')
//   }
//   return config
// }, error => {
//   return Promise.reject(error)
// })

/**
 * 响应拦截
 */
// http.interceptors.response.use(response => {
//   let token = Vue.cookie.get('token')
//   console.log('token in cookie is :', token)
//   let rspToken = response.headers['token']
//   console.log('token in response is :', rspToken)
//   if (YT.isEmpty(token)) {
//     Vue.cookie.set('token', rspToken, 1800)
//   } else {
//     if (token !== rspToken) {
//       Vue.cookie.remove('token')
//       router.push({ name: 'login' })
//     } else {
//       Vue.cookie.set('token', rspToken, 1800)
//     }
//   }
//   return response
// }, error => {
//   return Promise.reject(error)
// })

/**
 * get请求参数处理
 * @param {Object} params 参数对象
 * @param {Boolean} openDefultParams 是否开启默认参数
 * @returns {String}
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  let defaults = {
    't': new Date().getTime()
  }
  return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {Object} data 数据对象
 * @param {Boolean} openDefultdata 是否开启默认数据?
 * @param {String} contentType 数据格式
 * @returns {String}
 */
http.adornData = (data = {}, key, openDefultdata = true, contentType = 'json') => {
  let defaults = {
    't': new Date().getTime()
  }
  data = openDefultdata ? merge(defaults, data) : data
  let dataStr = contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
  // 报文加密处理
  if (http.isEncrypt()) {
    console.log('>>>>加密前数据：' + dataStr)
    // 数据加密
    dataStr = SecurityUtil.reqEncrypt(dataStr, key)
    console.log('>>>>加密后数据：' + dataStr)
  }
  return dataStr
}

/**
 * 发送post请求
 * @param {String} url 方法名称
 * @param {Object} params 数据对象
 * @param {Function} success 成功回调方法
 */
http.post = (url, params, success) => {
  let aesKey = ''
  if (http.isEncrypt()) {
    aesKey = SecurityUtil.getKey(16)
  }
  // 开启等待层
  YT.openWaitPanel()
  http({
    url: http.dataUrl(url),
    method: 'post',
    data: http.adornData(params, aesKey)
  }).then(res => {
    console.log('Server Back Code', res.status)
    YT.closeWaitPanel()
    let _rpdata = ''
    if (http.isEncrypt()) {
      // 返回报文解密
      try {
        console.log('>>>>解密前数据：' + res.data)
        let _decData = SecurityUtil.respDecrypt(res.data, aesKey)
        console.log('>>>>解密后数据：' + _decData)
        _rpdata = JSON.parse(_decData)
      } catch (error) {
        console.log(error)
        YT.alertInfo('系统异常，请稍后重试')
      }
    } else {
      _rpdata = res.data
    }
    http.succFun(success, _rpdata)
  }).catch(error => {
    // 关闭等待层
    YT.closeWaitPanel()
    YT.alertInfo('Server Error')
    if (error.response) {
      console.log('Server Error', error.response.status)
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message)
    }
    console.log(error.config)
  })
}

/**
 * 交易返回处理
 * @param {Function} success 成功回调方法
 * @param {Object} rpdata 返回数据
 */
http.succFun = (success, rpdata) => {
  if (rpdata) {
    if (rpdata.STATUS === '005') {
      // 会话超时处理 跳转登录页面
      YT.alertInfoHandle('会话超时，请重新登录', action => {
        router.push('/')
      })
    } else {
      success(rpdata)
    }
  } else {
    YT.alertInfo('系统异常，请稍后重试')
  }
}
export default http
